//=======================================================================
//		Copyright (c) 2011-2012 by MicroStrategy, Inc.  This copyrighted material
//		is the confidential, unpublished property of MicroStrategy.  This
//		copyright notice and any other copyright notices included in machine
//		readable copies must be reproduced on all authorized copies.
//
//		File:	default.js
//
//		Date:	Monday, May 16, 2011
//
//		Desc:	Default JScript data and methods.
//=======================================================================

// global variables
var g_oWizard;

function SetUpDebug()
{
    try
    {
        g_oWizard = wizard;
    }
    catch(e)
    {
        g_oWizard = window.external;
    }
    
    g_oWizard.ReportError("Break Me!")
}

function OnFinish(selProj, selObj)
{
	try
	{
	    // used for debugging only
	    //SetUpDebug();
	    
		var strProjectPath = wizard.FindSymbol('PROJECT_PATH');
		var strProjectName = wizard.FindSymbol('PROJECT_NAME');

		selProj = CreateCustomProject(strProjectName, strProjectPath);
		AddConfig(selProj, strProjectName);
		AddFilters(selProj);

		var InfFile = CreateCustomInfFile();
		AddFilesToCustomProj(selProj, strProjectName, strProjectPath, InfFile);
		PchSettings(selProj);
		InfFile.Delete();

		selProj.Object.Save();
	}
	catch(e)
	{
		if (e.description.length != 0)
			SetErrorInfo(e);
		return e.number
	}
}

function CreateCustomProject(strProjectName, strProjectPath)
{
	try
	{
		var strProjTemplatePath = wizard.FindSymbol('PROJECT_TEMPLATE_PATH');
		var strProjTemplate = '';
		strProjTemplate = strProjTemplatePath + '\\default.vcproj';

		var Solution = dte.Solution;
		var strSolutionName = "";
		if (wizard.FindSymbol("CLOSE_SOLUTION"))
		{
			Solution.Close();
			strSolutionName = wizard.FindSymbol("VS_SOLUTION_NAME");
			if (strSolutionName.length)
			{
				var strSolutionPath = strProjectPath.substr(0, strProjectPath.length - strProjectName.length);
				Solution.Create(strSolutionPath, strSolutionName);
			}
		}

		var strProjectNameWithExt = '';
		strProjectNameWithExt = strProjectName + '.vcproj';

		var oTarget = wizard.FindSymbol("TARGET");
		var prj;
		if (wizard.FindSymbol("WIZARD_TYPE") == vsWizardAddSubProject)  // vsWizardAddSubProject
		{
			var prjItem = oTarget.AddFromTemplate(strProjTemplate, strProjectNameWithExt);
			prj = prjItem.SubProject;
		}
		else
		{
			prj = oTarget.AddFromTemplate(strProjTemplate, strProjectPath, strProjectNameWithExt);
		}
		return prj;
	}
	catch(e)
	{
		throw e;
	}
}

function AddFilters(proj)
{
	try
	{
		// Add the folders to your project
		var strFilter = wizard.FindSymbol('SOURCE_FILTER');
		var group = proj.Object.AddFilter('Source Files');
		group.Filter = strFilter;
		
		strFilter = wizard.FindSymbol('HEADER_FILTER');
		group = proj.Object.AddFilter('Header Files');
		group.Filter = strFilter;
		
		strFilter = wizard.FindSymbol('RESOURCE_FILTER');
		group = proj.Object.AddFilter('Resource Files');
		group.Filter = strFilter;
		
		var strProjectName = wizard.FindSymbol('PROJECT_NAME');
		var strMIDL_HFile = strProjectName + '.h';
		var strMIDL_IFile = strProjectName + '_i.c';
		group = proj.Object.AddFilter('Generated Files');
		if(group)
		{
			group.SourceControlFiles = false;
			group.AddFile(strMIDL_HFile);
			var file = group.AddFile(strMIDL_IFile);
            
			// disable pch for Debug configuration
			var fileConfig = file.FileConfigurations('Debug');
			fileConfig.Tool.UsePrecompiledHeader = pchNone;
            
			// disable pch for Release configuration
			fileConfig = file.FileConfigurations('Release');
			fileConfig.Tool.UsePrecompiledHeader = pchNone;
		}
		else
		{
			// treat this as error instead?
			proj.Object.AddFile(strMIDL_HFile);
			proj.Object.AddFile(strMIDL_IFile);
		}
	}
	catch(e)
	{
		throw e;
	}
}

function AddConfig(proj, strProjectName)
{
	try
	{
		var strRInclsPath = wizard.FindSymbol('R_INCLS_LOCATION');
		
	    // add common config settings
	    AddCommonConfig(proj, strProjectName);
	    
	    // access Debug configuration
		var config = proj.Object.Configurations('Debug');
		config.IntermediateDirectory = '$(ConfigurationName)';
		config.OutputDirectory = '$(ConfigurationName)';
		config.ConfigurationType = ConfigurationTypes.typeDynamicLibrary;
		config.useOfATL = useOfATL.useATLDynamic;
		config.CharacterSet = charSetUNICODE;

		// Add compiler settings
		var CLTool = config.Tools('VCCLCompilerTool');
		CLTool.PreprocessorDefinitions = 'WIN32;_WINDOWS;_DEBUG;_USRDLL';
		if(strRInclsPath != "")
		    CLTool.AdditionalIncludeDirectories = strRInclsPath;

		// Add linker settings
		var LinkTool = config.Tools('VCLinkerTool');
		LinkTool.ModuleDefinitionFile = '.\\$(InputName).def';
		
		// Add MIDL settings
		var MIDLTool = config.Tools('VCMIDLTool');
		MIDLTool.PreprocessorDefinitions = '_DEBUG';
		MIDLTool.HeaderFileName = '.\\$(ProjectName).h';
		MIDLTool.TypeLibraryName = '.\\$(ProjectName).tlb';
		MIDLTool.InterfaceIdentifierFileName = '$(ProjectName)_i.c';

        // access Release configuration
		config = proj.Object.Configurations('Release');
		config.IntermediateDirectory = '$(ConfigurationName)';
		config.OutputDirectory = '$(ConfigurationName)';
		config.ConfigurationType = ConfigurationTypes.typeDynamicLibrary;
		config.useOfATL = useOfATL.useATLDynamic;
		config.CharacterSet = charSetUNICODE;

		// Add compiler settings
		var CLTool = config.Tools('VCCLCompilerTool');
		CLTool.PreprocessorDefinitions = 'WIN32;_WINDOWS;NDEBUG;_USRDLL';
		if (strRInclsPath != "")
		    CLTool.AdditionalIncludeDirectories = strRInclsPath;

		// Add linker settings
		var LinkTool = config.Tools('VCLinkerTool');
		LinkTool.ModuleDefinitionFile = '.\\$(InputName).def';
		
		// Add MIDL settings
		var MIDLTool = config.Tools('VCMIDLTool');
		MIDLTool.PreprocessorDefinitions = 'NDEBUG';
		MIDLTool.HeaderFileName = '.\\$(ProjectName).h';
		MIDLTool.TypeLibraryName = '.\\$(ProjectName).tlb';
		MIDLTool.InterfaceIdentifierFileName = '$(ProjectName)_i.c';
	}
	catch(e)
	{
		throw e;
	}
}

function PchSettings(proj)
{
	SetCommonPchSettings(proj);
}

function DelFile(fso, strWizTempFile)
{
	try
	{
		if (fso.FileExists(strWizTempFile))
		{
			var tmpFile = fso.GetFile(strWizTempFile);
			tmpFile.Delete();
		}
	}
	catch(e)
	{
		throw e;
	}
}

function CreateCustomInfFile()
{
	try
	{
		var fso, TemplatesFolder, TemplateFiles, strTemplate;
		fso = new ActiveXObject('Scripting.FileSystemObject');

		var TemporaryFolder = 2;
		var tfolder = fso.GetSpecialFolder(TemporaryFolder);
		var strTempFolder = tfolder.Drive + '\\' + tfolder.Name;

		var strWizTempFile = strTempFolder + "\\" + fso.GetTempName();

		var strTemplatePath = wizard.FindSymbol('TEMPLATES_PATH');
		var strInfFile = strTemplatePath + '\\Templates.inf';
		wizard.RenderTemplate(strInfFile, strWizTempFile);

		var WizTempFile = fso.GetFile(strWizTempFile);
		return WizTempFile;
	}
	catch(e)
	{
		throw e;
	}
}

function GetTargetName(strName, strProjectName)
{
	try
	{
		var strSafeRoot = wizard.FindSymbol('safe_root');
		
		// set the name of the rendered file based on the template filename
		var strTarget = strName;

		if (strName == 'udfAll.cpp')
			strTarget = 'FPFunctions.cpp';
		if (strName == 'FPall.rgs')
		    strTarget = 'FP.rgs';
		if (strName == 'FPClasses_att.h')
		    strTarget = 'FPClasses.h';
		if ((strName == 'DllRoot.cpp') || (strName == 'DllRoot_att.cpp'))
		    strTarget = strSafeRoot + '.cpp';
		if (strName == 'DllRoot._idl')
		    strTarget = strSafeRoot + '.idl';
		if (strName == 'DlgAll._rc')
		    strTarget = strSafeRoot + '.rc';
		if (strName == 'Root.def')
		    strTarget = strSafeRoot + '.def';
		if (strName == 'Root.pds')
		    strTarget = strSafeRoot + '.pds';

		return strTarget; 
	}
	catch(e)
	{
		throw e;
	}
}

/******************************************************************************
 Description: Delete file using file system object. 
******************************************************************************/
function SafeDeleteFile(strFilespec)
{
    var fso;
    fso = new ActiveXObject("Scripting.FileSystemObject");

    if(fso.FileExists(strFilespec))
    {
        var tmpFile = fso.GetFile(strFilespec);
        tmpFile.Delete();
    }
}

function AddFilesToCustomProj(proj, strProjectName, strProjectPath, InfFile)
{
	try
	{
		var projItems = proj.ProjectItems

		var strTemplatePath = wizard.FindSymbol('TEMPLATES_PATH');

		var strTpl = '';
		var strName = '';

		var strTextStream = InfFile.OpenAsTextStream(1, -2);
		while (!strTextStream.AtEndOfStream)
		{
			strTpl = strTextStream.ReadLine();
			if (strTpl != '')
			{
				strName = strTpl;
				var strTarget = GetTargetName(strName, strProjectName);
				var strTemplate = strTemplatePath + '\\' + strTpl;
				var strFile = strProjectPath + '\\' + strTarget;
				var strTempFile = strFile + ".tmp";

				var bCopyOnly = false;  //"true" will only copy the file from strTemplate to strTarget without rendering/adding to the project
				var strExt = strName.substr(strName.lastIndexOf("."));
				if(strExt==".bmp" || strExt==".ico" || strExt==".gif" || strExt==".rtf" || strExt==".css")
					bCopyOnly = true;
					
				// render template twice (second render needed to resolve symbol references within loops)
				wizard.RenderTemplate(strTemplate, strTempFile, bCopyOnly);
				wizard.RenderTemplate(strTempFile, strFile, bCopyOnly);
				
				// delete temporary file used for first render
				SafeDeleteFile(strTempFile);
				
				// add file to project
				proj.Object.AddFile(strFile);
			}
		}
		strTextStream.Close();
	}
	catch(e)
	{
		throw e;
	}
}
